<?php

namespace Admin\Frontend\Controllers;

use Admin\Models\app\XhappSchoolRelate;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\app\XhappReleasePlan;
use Admin\Models\user\XhsysUser;
use Helpers\HttpClient;
use Helpers\Tool;
use Helpers\Main;
use Helpers\Template;
use Helpers\User;
use Helpers\UserPower;
use Helpers\Assets;

class AppreleaseController extends ControllerBase
{
    private $enum = [];
    private $table = [
        '1' =>['keyValue' => 'sAppId', 'sDepName1' => 'tReleaseDate', 'iconCls1' => 'fa fa-calendar',
            'sDepName2' => 'sAppName', 'iconCls2' => 'fa fa-cube', 'sql' => 'sAppId'],
        '2' =>['keyValue' => 'tReleaseDate', 'sDepName1' => 'sAppName', 'iconCls1' => 'fa fa-cube',
            'sDepName2' => 'tReleaseDate', 'iconCls2' => 'fa fa-calendar', 'sql' => 'tReleaseDate']
    ];
    private $planAppEnum    = [
        'bApprove'      => [0 => '<i class="fa fa-ban" title="未确认" style="color:red;"></i>', 1 => '<i class="fa fa-check" title="已确认" style="color:green;"></i>']
    ];
    private $appEnum = ['userType' => [1 => '学生', 2 => '教师', 3 => '家长', 4 => '通用']];

    private function getEnum()
    {
        $this->enum['sAppId'] = $this->getAppList();
        return $this->enum;
    }
    private $listEnum = ['bDownLoad' => ['0' => '未执行', '1' => '已执行'],'bInstall' => ['0' => '未执行', '1' => '已执行']];

    /**
     * 应用发布计划列表页面
     *
     * @return mixed
     *
     * create by qgz 2018/4/13
     */
    public function planAction()
    {
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::select2();
        Assets::easyUI('js/appserver/appReleaseList.js');
        UserPower::checkUserPower('App_Release_Plan') or die(Main::showMessageModal('对不起，您没有查看此页面的权限！'));
        $listSearchArr = $listButtonArr = [];
        if (UserPower::checkUserPower('App_Release_Plan_Add')) {
            $listButtonArr[] = ['id' => 'bt_list_add', 'text'=>'添加', 'plain'=>'true', 'icon'=>'fa-plus'];
        }
        if (UserPower::checkUserPower('App_Release_Plan_Del')) {
            $listButtonArr[] = ['id' => 'bt_list_del', 'text' => '删除', 'plain' => 'true', 'icon' => 'fa-trash'];
        }
        if (UserPower::checkUserPower('App_Release_Plan_Edit')) {
            $listButtonArr[] = ['id' => 'bt_list_school', 'text'=>'修改学校', 'icon'=>'fa-cogs'];
        }
        $listSearchArr[] = ['type'=>'select', 'id'=>'list_search_type', 'style' => 'width: 70px;',
            'data' => ['1' => '未完成', '2' =>'已完成']];
        $listSearchArr[] = ['type'=>'text', 'id'=>'list_vague', 'label'=>' 搜索: '];
        $listSearchArr[] = ['type'=>'text', 'id'=>'list_create_start', 'class' => 'easyui-datebox',
            'style' => 'width: 100px;', 'label'=>' 发布时间: '];
        $listSearchArr[] = ['type'=>'text', 'id'=>'list_create_end', 'class' => 'easyui-datebox',
            'style' => 'width: 100px;', 'label'=>' ~ '];
        $listSearchArr[] = ['type'=>'button', 'id'=>'bt_list_search', 'text' => '查找',
            'icon'=>'fa-search', 'style'=>'margin-left:10px'];
        if (UserPower::checkUserPower('App_Release_Plan_Add')) {
            $formButtonArr[] = array('id' => 'bt_form_add', 'text' => '下一步', 'class' => 'disabled');
        }
        if (UserPower::checkUserPower('App_Release_Plan_Edit')) {
            $formButtonArr[] = array('id' => 'bt_form_edit', 'text' => '修改');
        }
        $formButtonArr[] = array('id' => 'bt_form_reset', 'text' => '重置');
        $formButtonArr[] = array('id' => 'bt_form_back', 'text' => '返回');
        return $this->view->setVars([
            'List'          => Template::createList('list', 'App_Release_List', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
                'tableAttr'     => ['rownumbers' => 'false']
            ]),
            'Form'          => Template::createForm('App_ReleaseCreate', $this->getEnum()),
            'FormButton'    => Template::createButtonToolBar($formButtonArr)
        ]);
    }

    /**
     * 根据页码及每页行数获取数据并以json格式返回
     *
     * @return mixed
     *
     * create by qgz 2018/4/13
     */
    public function getListDataAction()
    {
        $startDate= $this->request->getPost('startDate', 'string');
        $endDate  = $this->request->getPost('endDate', 'string');
        $type  = $this->request->getPost('type');
        $parameters = [
            'conditions' => 'bDelete = 0 '
        ];
        if ($startDate) {
            $parameters['conditions'] .= " AND tReleaseDate >= '{$startDate}'";
        }
        if ($endDate) {
            $parameters['conditions'] .= " AND tReleaseDate <= '{$endDate}'";
        }
        if ($type && $type == 2) {
            $parameters['conditions'] .= "AND bInstall = 1";
        } else {
            $parameters['conditions'] .= "AND bInstall = 0";
        }
        try {
            Main::runSearchVagueConditions($parameters['conditions'], ['iAppCode', 'sAppName']);
            $parameters['conditions'] .= ' order by tReleaseDate DESC ';
            $data = Main::runModelPage('\\Admin\\Models\\app\\XhappReleasePlan', $parameters, $this->listEnum);
            if (empty($data['rows'])) {
                return $this->sendJsonResponse($data);
            }

            foreach ($data['rows'] as $value) {
                $createIds[] = $value['iCreateUserId'];
                $iIds[] = $value['iId'];
            }
            $createIds = implode(',', array_unique($createIds));
            $iIds = implode(',', $iIds);
            $user = $school = [];

            $usersArr = XhsysUser::find(['columns' => 'iUserId, sUserName',
                'conditions' => 'bDelete = 0 AND iUserId in ('.$createIds.')' ])->toArray();
            if ($usersArr) {
                foreach ($usersArr as $cloum) {
                    $user[$cloum['iUserId']] = $cloum['sUserName'];
                }
            }
            $schoolArr = XhappSchoolRelate::find([
                'columns' => 'iSchoolId, sSchoolName, iAppPlanId, count(*) AS count ',
                'conditions' => 'iAppPlanId in ('.$iIds.') AND bDelete = 0 GROUP BY iAppPlanId HAVING count > -1 '])
                ->toArray();
            if ($schoolArr) {
                foreach ($schoolArr as $cloum) {
                    $school[$cloum['iAppPlanId']] = $cloum['count'];
                }
            }

            foreach ($data['rows'] as &$value) {
                $value['createName'] = $user&&$user[$value['iCreateUserId']] ? $user[$value['iCreateUserId']] : '';
                $value['schoolCount'] = $school&&$school[$value['iId']] ? $school[$value['iId']] : 0;
            }
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 选择学校页
     *
     * @return mixed
     *
     * create by qgz 2018/4/24
     */
    public function selectSchoolAction()
    {
        $this->view->setTemplateBefore('listlist');
        $groupId = $this->request->getQuery('iId', 'int');
        if (!$groupId) {
            return $this->sendViewError('缺少学校id');
        }
        Assets::easyUI('js/appserver/selectSchool.js');
        $outListSearchArr = [];
        $outListSearchArr[] = ['type' => 'text', 'id' => 'list_out_vague', 'label' => '搜索：'];
        $outListSearchArr[] = ['type' => 'button', 'id' => 'bt_list_out_search', 'text' => '查找', 'icon' => 'fa-search'];
        return $this->view->setVars([
            'inList'    => Template::createList('list_in', 'App_Release_SelectSchool', [
                'title'         => '已选择学校',
            ]),
            'outList'   => Template::createList('list_out', 'App_Release_SelectSchool', [
                'title'         => '未选择学校',
                'searchToolbar' => Template::createSearchToolBar($outListSearchArr)
            ]),
        ]);
    }

    /**
     * 获取学校列表
     *
     * @return mixed
     *
     * create by qgz 2018/4/13
     */
    public function getSchoolDataAction()
    {
        $iId = $this->request->getPost('iId', 'int');
        $type = $this->request->getPost('type', 'int');
        if (!$iId) {
            return $this->sendErrorResponse(400, '请先选择计划！');
        }
        if ($type == 2) {//所有学校列表
            $parameters = [
                'columns'    => 'iSchoolId,sSchoolName',
                'conditions' => 'bDelete = 0 AND (iStatus = 1 OR iStatus = 2) '
            ];
            try {
                $inSchoolData = XhappSchoolRelate::find([
                    'columns' => 'iSchoolId,sSchoolName',
                    'conditions' => 'bDelete = 0 AND iAppPlanId = :iId: ',
                    'bind' => ['iId' => $iId]
                ])->toArray();
                if ($inSchoolData) {//去掉已存在
                    $inSchoolData = implode(',', array_column($inSchoolData, 'iSchoolId'));
                    $parameters['conditions'] .= " AND iSchoolId NOT IN ({$inSchoolData})";
                }
                Main::runSearchVagueConditions($parameters['conditions'], ['iSchoolId', 'sSchoolName']);
                $data = Main::runModelPage('\\Admin\\Models\\school\\XhschoolInfo', $parameters);
                $publicClass = $this->getPublicClass($iId);
                foreach ($data as $key => &$datum) {
                    if ($key == 'rows') {
                        foreach ($datum as &$value) {
                            if ($publicClass && in_array($value['iSchoolId'], array_keys($publicClass))) {
                                $value['isPublicClass'] = '1';
                                $value['publicClass'] = $publicClass[$value['iSchoolId']];
                                //$value['publicClass'] .= '<div style="width: 100px;word-wrap: break-word; background-color: yellow" title="'.$publicClass[$value['iSchoolId']].'">'.$publicClass[$value['iSchoolId']].'</div>';
                            } else {
                                $value['isPublicClass'] = '0';
                                $value['publicClass'] = '';
                            }
                        }
                    }
                }
                return $this->sendJsonResponse($data);
            } catch(\Exception $e) {
                return $this->sendErrorResponse(500, $e->getMessage());
            }

        } else {//已选择
            $parameters  = [
                'columns' => 'iSchoolId,sSchoolName',
                'conditions' => 'bDelete = 0 AND iAppPlanId = :iId: ',
                'bind' => ['iId' => $iId]
            ];
            try {
                Main::runSearchVagueConditions($parameters['conditions'], ['iSchoolId', 'sSchoolName']);
                $data = Main::runModelPage('\\Admin\\Models\\app\\XhappSchoolRelate', $parameters);
                $publicClass = $this->getPublicClass($iId);
                foreach ($data as $key => &$datum) {
                    if ($key == 'rows') {
                        foreach ($datum as &$value) {
                            if ($publicClass && in_array($value['iSchoolId'], array_keys($publicClass))) {
                                $value['isPublicClass'] = '1';
                                $value['publicClass'] = $publicClass[$value['iSchoolId']];
                            } else {
                                $value['isPublicClass'] = '0';
                                $value['publicClass'] = '';
                            }
                        }
                    }
                }
                return $this->sendJsonResponse($data);
            } catch (\Exception $e) {
                return $this->sendErrorResponse(500, $e->getMessage());
            }

        }
    }

    /**
     * 获取公开课信息
     * @param $iId
     * @return array
     * @throws \Exception
     *
     * create by qgz 2018/4/13
     */
    public function getPublicClass($iId)
    {
        $return = [];
        $sql = "SELECT a.iPCId, a.iUserId, a.tStartTime, b.iUserId, b.sUserName, b.iSchoolId
                FROM Admin\Models\school\XhschoolPublicClass a, Admin\Models\user\XhsysUser b
                WHERE a.bDelete = 0
                AND b.bDelete = 0
                AND a.iUserId = b.iUserId
                AND b.iSchoolId in (
                    SELECT
                        c.iSchoolId
                    FROM
                        Admin\Models\user\XhsysUser c,
                        Admin\Models\school\XhschoolPublicClass d
                    WHERE
                        c.bDelete = 0
                    AND d.bDelete = 0
                    AND c.iUserId = d.iUserId
                    AND DATE_FORMAT(d.tStartTime, '%Y-%m-%d') IN (
                        SELECT
                            tReleaseDate
                        FROM
                            Admin\Models\app\XhappReleasePlan
                        WHERE
                            iId = $iId
                    )
                ) 
                AND DATE_FORMAT(a.tStartTime, '%Y-%m-%d') >= DATE_FORMAT(NOW(), '%Y-%m-%d')
                AND DATE_FORMAT(a.tStartTime, '%Y-%m-%d') >= (
                    SELECT tReleaseDate FROM Admin\Models\app\XhappReleasePlan WHERE iId = $iId 
                    )
                ORDER BY a.tStartTime ";

        try {
            $data = $this->modelsManager->executeQuery($sql)->toArray();
        } catch (\Exception $e) {
            throw $e;
        }
        if (!$data) {
            return $return;
        }
        foreach ($data as $item) {
            $return[$item['iSchoolId']][] = $item['tStartTime'];
        }
        foreach ($return as $key => $value) {
            $chunkArr = array_chunk($value, 2);
            foreach ($chunkArr as $k => &$v) {
                $chunkArr[$k] = '<div style="background-color: yellow" title="请注意该学校在这些日期内有公开课！">'.'['.implode('][', $v).']'.'</div>';
            }
            $return[$key] = implode('', $chunkArr);
        }
        return $return;
    }

    /**
     * 增加/减少学校列表
     *
     * @return mixed
     *
     * create by qgz 2018/4/24
     */
    public function modifySchoolListAction()
    {
        $iAppPlanId = $this->request->getPost('iId', 'int');
        $type = $this->request->getPost('type', 'int');
        $schoolIdArr = $this->request->getPost('schoolId');

        $userid = User::getId();
        $modifyTime = date('Y-m-d H:i:s', time());
        $schoolIds = implode(',', $schoolIdArr);

        try {
            $this->db->begin();
            if ($type == 1) {//增加学校
                $parameters  = [
                    'columns' => 'iId',
                    'conditions' => "bDelete = 1 AND iAppPlanId = {$iAppPlanId} AND iSchoolId in ({$schoolIds})",
                ];
                $haveInData = XhappSchoolRelate::find($parameters)->toArray();
                if ($haveInData) {
                    $haveInIds = implode(',', array_column($haveInData, 'iId'));
                    $sql = "UPDATE Admin\Models\app\XhappSchoolRelate SET bDelete = 0 , bApprove = 0, iLastModifyUserId = $userid , tLastModifyDate = "."'".$modifyTime."'"." WHERE iId in ($haveInIds) " ;
                    if (!$this->modelsManager->executeQuery($sql)) {
                        $this->db->rollback();
                        return $this->sendErrorResponse(500, '添加出错!');
                    }
                    $schoolIdArr = array_diff($schoolIdArr, $haveInIds);
                }

                if ($schoolIdArr) {
                    $schoolData =  XhschoolInfo::getSchoolSupportArray();
                    $xhSchoolReleate = new XhappSchoolRelate();
                    $data = [
                        'iAppPlanId' => $iAppPlanId,
                        'iCreateUserId' => $userid,
                        'tCreateDate' => $modifyTime,
                        'iLastModifyUserId' => $userid,
                        'tLastModifyDate' => $modifyTime
                    ];
                    foreach ($schoolIdArr as $schoolId) {
                        $data['iSchoolId'] = $schoolId;
                        $data['sSchoolName'] = $schoolData[$schoolId];
                        $clone = clone $xhSchoolReleate;
                        if (!$clone->create($data)) {
                            $this->db->rollback();
                            return $this->sendErrorResponse(500, '添加出错!');
                        }
                    }
                }
                $this->db->commit();
                return $this->sendSuccessResponse('成功！');
            } else {//减少学校
                $findData = XhappReleasePlan::findFirst([
                    'columns' => 'sAppId, sPlanId, bDownLoad, bInstall',
                    'conditions' => 'bDelete = 0 AND iId = :iId: AND bDownLoad = 1',
                    'bind' => ['iId' => $iAppPlanId]
                ]);
                if ($findData) {//如果是已经下发下载任务，需要去掉任务中的这些学校
                    $planId = $findData->sPlanId;
                    $schoolIdArr = ['removeSchools' => $schoolIdArr];
                    $config = Main::getConfigByName('jAppServer');
                    $httpClient = new HttpClient($config['url']);
                    $response = $httpClient->post(sprintf('/api/v1/tasks/%s/schools/reduce', $planId), $schoolIdArr);
                    if (!$response->isSuccess()) {
                        $msg = json_decode($response->body, true);
                        Main::createCommitLog('apprelease', 'modifySchoolList', 'delSchool', ['post' => $this->request->getPost()], null, json_encode(['planid' => $planId, 'schoolids' => $schoolIdArr, 'return' => $msg['msg']]));
                        $this->db->commit();
                        return $this->sendErrorResponse(500, '去除出错,接口错误:'.$msg['msg']);
                    }
                }
                $sql = "UPDATE Admin\Models\app\XhappSchoolRelate SET bDelete = 1 , iLastModifyUserId = $userid , tLastModifyDate = "."'".$modifyTime."'"." WHERE iAppPlanId = {$iAppPlanId} AND iSchoolId in ({$schoolIds}) " ;
                if (!$this->modelsManager->executeQuery($sql)) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '去除出错!');
                } else {
                    $this->db->commit();
                    return $this->sendSuccessResponse('成功！');
                }
            }
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 获取应用发布计划详情
     *
     * @return mixed
     *
     * create by qgz 2018/4/13
     */
    public function getPlanInfoAction()
    {
        $iId= $this->request->getPost('iId', 'int');
        if (empty($iId)) {
            return $this->sendErrorResponse(500, '缺少iId!');
        }
        $data = XhappReleasePlan::findFirst($iId)->toArray();
//        $data['tReleaseDate'] = str_replace(' ', 'T', $data['tReleaseDate']);//展示时间格式化
        $data['version'] = ['id' => $data['sVersionCode'], 'text' => $data['sVersionName']];
        $data['bDownLoad'] = $this->listEnum['bDownLoad'][$data['bDownLoad']];
        $data['bInstall'] = $this->listEnum['bInstall'][$data['bInstall']];
        return $this->sendJsonResponse($data);
    }

    /**
     * 根据应用Id获取该应用的所有版本信息
     *
     * @return mixed
     *
     * create by qgz 2018/4/28
     */
    public function getVersionAction()
    {
        $return = [];
        $appid = $this->request->getQuery('appid', 'string');
        if (!$appid) {
            return $this->sendJsonResponse($data);
        }
        $data = $this->getAppInfo($appid);
        if (!empty($data['sAppVersion'])) {
            $versions = $data['sAppVersion'];
            array_multisort(array_keys($versions),SORT_DESC,$versions);
            foreach ($versions as $key => $value) {
                $return[] = ['id' => $key, 'text' => $value];
            }
        }
        return $this->sendJsonResponse($return);
    }

    /**
     * 增加或修改应用发布信息
     *
     * @return mixed
     *
     * create by qgz 2018/4/13
     */
    public function saveReleasePlanAction()
    {
        $iId = $this->request->getPost('iId', 'int');
        $sAppId = $this->request->getPost('sAppId', 'string');
        $tReleaseDate = $this->request->getPost('tReleaseDate', 'string');
        $mReMark = $this->request->getPost('mReMark', 'string');
        $versionId = $this->request->getPost('version');

        if (empty($tReleaseDate)) {
            return $this->sendErrorResponse(400, '时间格式不正确！');
        }
        try {
            $appInfo = $this->getAppInfo($sAppId);
            if (empty($appInfo)) {
                return $this->sendErrorResponse(400, '没有应用的信息！');
            }
            $schoolData =  XhschoolInfo::getSchoolSupportArray();
            $userid = User::getId();
            $modifyTime = date('Y-m-d H:i:s', time());

            if ($iId){//修改
                $xhReleasePlan = XhappReleasePlan::findFirst($iId);
                $xhReleasePlan->sAppId = $sAppId;
                $xhReleasePlan->iAppCode = $appInfo['appCode'];
                $xhReleasePlan->sAppName = $appInfo['name'];
                $xhReleasePlan->sPackageName = $appInfo['packageName'];
                $xhReleasePlan->tReleaseDate = $tReleaseDate;
                $xhReleasePlan->sVersionCode = $versionId;
                $xhReleasePlan->sVersionName = $appInfo['sAppVersion'][$versionId];
                $xhReleasePlan->mReMark = $mReMark;
                $xhReleasePlan->iLastModifyUserId = $userid;
                $xhReleasePlan->tLastModifyDate = $modifyTime;
                if (!$xhReleasePlan->save()){
                    return $this->sendErrorResponse(500, '修改出错！');
                }
                return json_encode([
                    'code' => 200,
                    'msg' => 'success',
                    'iId' => $xhReleasePlan->iId,
                    'appName' => $xhReleasePlan->sAppName,
                    'date' => $xhReleasePlan->tReleaseDate
                ]);
            }
            else {//新增
                $existcheck = XhappReleasePlan::findFirst(['conditions' => 'sAppId = :sAppId: and tReleaseDate = :tReleaseDate: and bDelete = 0', 'bind' => ['sAppId' => $sAppId, 'tReleaseDate' => $tReleaseDate]]);
                if ($existcheck){//该计划已经存在
                    return $this->sendErrorResponse(500,'计划已存在！');
                }
                else{//创建新计划
                    $xhReleasePlan = new XhappReleasePlan();
                    $xhReleasePlan->sAppId = $sAppId;
                    $xhReleasePlan->iAppCode = $appInfo['appCode'];
                    $xhReleasePlan->sAppName = $appInfo['name'];
                    $xhReleasePlan->sPackageName = $appInfo['packageName'];
                    $xhReleasePlan->tReleaseDate = $tReleaseDate;
                    $xhReleasePlan->sVersionCode = $versionId;
                    $xhReleasePlan->sVersionName = $appInfo['sAppVersion'][$versionId];
                    $xhReleasePlan->mReMark = $mReMark;
                    $xhReleasePlan->iCreateUserId = $userid;
                    $xhReleasePlan->tCreateDate = $modifyTime;
                    $xhReleasePlan->iLastModifyUserId = $userid;
                    $xhReleasePlan->tLastModifyDate = $modifyTime;
                    if (!$xhReleasePlan->save()){
                        return $this->sendErrorResponse(500, '创建错误!');
                    };
                    return json_encode([
                        'code' => 200,
                        'msg' => 'success',
                        'iId' => $xhReleasePlan->iId,
                        'appName' => $xhReleasePlan->sAppName,
                        'date' => $xhReleasePlan->tReleaseDate
                    ]);
                }
            }
        }catch (\Exception $e){
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }


    /**
     * 获取某个应用的详情
     *
     * @return array|bool|mixed|\stdClass
     *
     * create by qgz 2018/4/13
     */
    public function getAppInfo($appId)
    {
        $return = [];
        $config = Main::getConfigByName('jAppServer');
        $httpClient = new HttpClient($config['url']);
        if($appId) {
            $response = $httpClient->get(sprintf('/api/v1/applications/%s', $appId));
            $appInfo  = $response->toArray();
            if($response->isSuccess() && !empty($appInfo)){
                if (!empty($appInfo['appVersions'])){
                    foreach ($appInfo['appVersions'] as $value){
                        $appInfo['sAppVersion'][$value['versionCode']] = $value['versionName'];
                    }
                }
            }
            return $appInfo;
        }
        return $return;
    }

    /**
     * 获取应用列表
     *
     * @return array
     *
     * create by qgz 2018/4/13
     */
    public function getAppList(){
        $return = [];
        $params     = [
            'page'      => 1,
            'size'      => 2
        ];
        $data = $this->getAppListData($params);
        if (empty($data)){
            return $return;
        }
        $params['size'] = $data['totalElements'];
        $data = $this->getAppListData($params);
        if (empty($data)){
            return $return;
        }
        foreach ($data['content'] as $appInfo){
            if (strpos($appInfo['name'], '(学生)') === false && strpos($appInfo['name'], '(教师)') === false
                && strpos($appInfo['name'], '(通用)') === false && strpos($appInfo['name'], '(家长)') === false
                && strpos($appInfo['name'], '（学生端）') === false
            ){
                $return[$appInfo['appId']] = iconv('UTF-8', 'GBK', $appInfo['name'].'('.$this->appEnum['userType'][$appInfo['userType']].')');
            }else{
                $return[$appInfo['appId']] = iconv('UTF-8', 'GBK', $appInfo['name']);
            }

        }
        asort($return);
        foreach ($return as $key=>$value){
            $return[$key] = iconv('GBK', 'UTF-8', $value);
        }
        return $return = ['' => '--请选择--'] + $return;
    }

    /**
     * 获取应用列表数据
     *
     * @return array|bool|mixed|\stdClass
     *
     * create by qgz 2018/4/13
     */
    public function getAppListData($params){
        $return = [];
        $config = Main::getConfigByName('jAppServer');
        $httpClient = new HttpClient($config['url']);
        $response = $httpClient->get('/api/v1/applications/', $params);
        $body     = $response->toArray();
        if(!empty($body) || $body['totalElements'] === null || $body['content'] === null){
            return $body;
        }
        return $return;
    }

    /**
     * 删除应用发布
     *
     * @return mixed
     *
     * create by qgz 2018/4/13
     */
    public function delReleasePlanAction()
    {
        $iId = $this->request->getPost('iId');
        if (empty($iId)){
            return $this->sendErrorResponse(400, '请选择计划！');
        }
        $iId = "(".implode(",", $iId).")";
        $userid = User::getId();
        $modifyTime = date('Y-m-d H:i:s', time());
        try{
            $this->db->begin();
            //删除计划表数据
            $sql = "UPDATE Admin\Models\app\XhappReleasePlan 
                    SET bDelete = 1, iLastModifyUserId = $userid , tLastModifyDate = "."'".$modifyTime."'"." 
                    WHERE iId in $iId";
            if (!$this->modelsManager->executeQuery($sql)){
                $this->db->rollback();
                return $this->sendErrorResponse(500, '删除计划表出错!');
            }
            //删除学校表数据
            $sql = "UPDATE Admin\Models\app\XhappSchoolRelate 
                    SET bDelete = 1, iLastModifyUserId = $userid , tLastModifyDate = "."'".$modifyTime."'"." 
                    WHERE iAppPlanId in $iId";
            if (!$this->modelsManager->executeQuery($sql)){
                $this->db->rollback();
                return $this->sendErrorResponse(500, '删除学校表出错!');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('成功！');
        }catch (\Exception $e){
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 发布进度主页面
     *
     *
     * create by qgz 2018/4/28
     */
    public function progressAction(){
        Assets::easyUI();
        Main::showNavPosition();
        UserPower::checkUserPower('App_Release_Progress') or die(Main::showMessageModal('对不起，您没有查看此页面的权限！'));
        $this->view->pick('appserver/appReleaseIndex');
    }

    /**
     * 发布进度table页
     *
     *
     * create by qgz 2018/4/28
     */

    public function indexTableAction()
    {
        Assets::easyUI('js/appserver/appReleasePlan.js');
        Main::showNavPosition();
        $this->view->pick('appserver/appReleasePlan');
        $tableType = $this->request->getQuery('type');
        Template::exists('App_Release_Plan', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
        $listButtonArr = $formButtonArr = $listSearchArr = array();
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        if ($tableType == 1 && UserPower::checkUserPower('App_Release_Progress_Check')){
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_agree', 'text' => '确认', 'icon' => 'fa-check-square-o', 'disabled' => true);
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_deleted', 'text' => '删除学校', 'icon' => 'fa-trash', 'disabled' => true);
            $check = true;
        }else{
            $check = false;
        }
        $this->view->setVars(array(
            'staffList' => Template::createList('dataList', 'App_Release_Plan', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
                'checkbox' => $check
            ]),
            'type' => $tableType
        ));
    }

    /**
     * 获取左侧计划树
     *
     * @return mixed
     *
     * create by qgz 2018/4/28
     */
    public function getAppDeptListAction()
    {
        $data = [];
        $type = $this->request->getQuery('tableType');
        if (empty($type)){
            return $this->sendJsonResponse($data);
        }
        $sql = 'SELECT * FROM Admin\Models\app\XhappReleasePlan as a WHERE a.bDelete = 0 AND a.iId IN ( SELECT iAppPlanId FROM Admin\Models\app\XhappSchoolRelate as b WHERE b.bDelete = 0 ) ORDER BY a.tReleaseDate DESC ';
        try {
            $data = $this->modelsManager->executeQuery($sql)->toArray();
        }
        catch (\Exception $e){
            return $this->sendErrorResponse(500, $e->getMessage());
        }
        $data = $this->getDept($data, $type);
        return $this->sendJsonResponse(array($data));
    }

    /**
     * 获取左侧树数据
     *
     * @return array
     *
     * create by qgz 2018/4/28
     */
    public function getDept($data_arr, $type)
    {
        $return = [
            'iDepId' => 0,
            'sDepName' => '全部',
            'iconCls' => 'fa fa-list-ul',
            'children' => [],
            'tableType' => $type,//类型，按应用和时间分类
        ];
        if (!is_array($data_arr) || empty($data_arr))
        {
            $return['deptType'] = 3;//没有数据
            return $return;
        }

        $date_name_arr = $date_name = [];
        foreach ($data_arr as $value){
            $date_name_arr[$value[$this->table[$type]['keyValue']]][] = $value;
            $progress_arr[$value[$this->table[$type]['keyValue']]][$value['iId']] = $value['sPlanId'];
        }
        $getPrograssData = $this->getPrograssData($progress_arr, $type);
        foreach ($date_name_arr as $id => $item){
            foreach ($item as &$row){
                $row['iDepId'] = $row['iId'];
                $row['sDepName'] = $row[$this->table[$type]['sDepName1']];
                $row['iParentId'] = $id;
                $row['iconCls'] = $this->table[$type]['iconCls1'];
                $row['children'] = [];
                $row['deptType'] = 2;//二级节点
                $row['tableType'] = $type;//table类型
                $row['download'] = $this->getBar($getPrograssData[$id][$row['iId']]['downloadedUserNum'], $getPrograssData[$id][$row['iId']]['totalUserNum']);
                $row['install'] = $this->getBar($getPrograssData[$id][$row['iId']]['executedUsersNum'], $getPrograssData[$id][$row['iId']]['totalUserNum']);
            }

            $date_name[$id]['iDepId'] = $id;
            $date_name[$id]['sDepName'] = $item[0][$this->table[$type]['sDepName2']];
            $date_name[$id]['iParentId'] = 0;
            $date_name[$id]['iconCls'] = $this->table[$type]['iconCls2'];
            $date_name[$id]['children'] = $item;
            $date_name[$id]['state'] = 'closed';
            $date_name[$id]['deptType'] = 1;//一级节点
            $date_name[$id]['tableType'] = $type;//table类型
            $date_name[$id]['download'] = $this->getBar($getPrograssData[$id]['downloadedUserNum'], $getPrograssData[$id]['totalUserNum']);
            $date_name[$id]['install'] = $this->getBar($getPrograssData[$id]['executedUsersNum'], $getPrograssData[$id]['totalUserNum']);
        }
        $return['children'] = array_values($date_name);
        return $return;
    }

    /**
     * 获取进度数据
     *
     * @return mixed
     *
     * create by qgz 2018/4/28
     */
    public function getPrograssData($arr, $type){
        $config = Main::getConfigByName('jAppServer');
        $httpClient = new HttpClient($config['url']);
        $totalUserNum = $downloadedUserNum = $executedUsersNum = [];
        foreach ($arr as $key => $value){
            $fina[$key]['totalUserNum'] = $fina[$key]['downloadedUserNum'] = $fina[$key]['executedUsersNum'] = 0;
            foreach ($value as $k => $v){
                $fina[$key][$k]['totalUserNum'] = $fina[$key][$k]['downloadedUserNum'] = $fina[$key][$k]['executedUsersNum'] = 0;
                if (!$v){
                    continue;
                }
                $response = $httpClient->get(sprintf('/api/v1/tasks/%s', $v));
                if($response->isSuccess()){
                    $appInfo  = $response->toArray();
                    $fina[$key][$k]['totalUserNum'] = $appInfo['totalUserNum'];
                    $fina[$key][$k]['downloadedUserNum'] = $appInfo['downloadedUserNum'];
                    $fina[$key][$k]['executedUsersNum'] = $appInfo['executedUsersNum'];
                    $fina[$key]['totalUserNum'] += $appInfo['totalUserNum'];
                    $fina[$key]['downloadedUserNum'] += $appInfo['downloadedUserNum'];
                    $fina[$key]['executedUsersNum'] += $appInfo['executedUsersNum'];
                }else{//进日志
                    Main::createCommitLog('apprelease', 'progress', 'getProgressError', [], null, ['请求接口'=>sprintf('/api/v1/tasks/%s', $v),'任务id'=>$v, '返回值' => $response]);
                }
            }
        }
        return $fina;
    }

    /**
     * 获取进度条显示
     *
     * @return string
     *
     * create by qgz 2018/4/28
     */
    public function  getBar($num, $total){
        $precent = ($num != 0 && $total != 0) ? ($num/$total)*100 : 0;
        return '<div style="height:8px"></div><div><div class="progress" style="align=center; margin: auto;top:0;left:0;right:0;bottom:0; background-color:lightgray;"><div style="background-color:red; width: '.$precent.'%;height:100%"></div></div></div>'."<div style="."\"font-size:1%\"".">$num/$total</div>";
    }

    /**
     * 获取选中计划的相关学校
     *
     * @return mixed
     *
     * create by qgz 2018/4/28
     */
    public function getAppReleasePlanDataAction()
    {
        $key = $this->request->getPost('key');
        $depttype = $this->request->getPost('depttype');
        $tabletype = $this->request->getPost('tabletype');
        $depId = $this->request->getPost('depId');

        $sql = 'SELECT b.iId, b.iSchoolId, b.sSchoolName, b.bApprove, a.iId as id, a.iAppCode, a.sAppName, a.sPlanId, a.tReleaseDate, a.sVersionCode, a.mReMark, b.iCreateUserId, b.tCreateDate, c.sUserName 
                FROM XHApp_ReleasePlan a, XHApp_SchoolRelate b, XHSys_User c 
                WHERE b.iAppPlanId = a.iId 
                AND a.bDelete = 0 
                AND b.bDelete = 0 
                AND a.iCreateUserId = c.iUserId';
        if ($depttype == '1'){
            $sql .= " AND a.".$this->table[$tabletype]['sql']." = '".$depId."'";
        }
        elseif ($depttype == '2'){
            $sql .=" AND a.iId = "."'".$depId."'";
        }
        if (trim($key)){
            $sql .=" AND b.sSchoolName like '%".trim($key)."%'";
        }
        try {
            $data = Main::runSqlPage(['query'=>"select :columns: from ({$sql}) as t",'columns'=>'t.*'],$this->planAppEnum);
            if ($data['total'] != 0){
                $schoolInfo = $this->getSchoolProgress($data['rows']);//获取学校的详细进度
                foreach ($data['rows'] as &$value){
                    if ($value['sPlanId'] && !empty($schoolInfo) && isset($schoolInfo[$value['sPlanId']]) && isset($schoolInfo[$value['sPlanId']][$value['iSchoolId']])){
                        $value['download'] = $this->getBar($schoolInfo[$value['sPlanId']][$value['iSchoolId']]['downloadedUserNum'], $schoolInfo[$value['sPlanId']][$value['iSchoolId']]['totalUserNum']);
                        $value['install'] = $this->getBar($schoolInfo[$value['sPlanId']][$value['iSchoolId']]['executedUserNum'], $schoolInfo[$value['sPlanId']][$value['iSchoolId']]['totalUserNum']);
                    }else{
                        $value['download'] = $this->getBar(0, 0);
                        $value['install'] = $this->getBar(0, 0);
                    }
                }
            }
            return $this->sendJsonResponse($data);
        }
        catch (\Exception $e){
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    public function getSchoolProgress($data){
        $deal = $return = [];
        if (!empty($data)){
            foreach ($data as $value){
                if ($value['sPlanId']){
                    $deal[$value['sPlanId']][] = $value['iSchoolId'];
                }
            }
        }
        if (!empty($deal)){
            try{
                $config = Main::getConfigByName('jAppServer');
                $httpClient = new HttpClient($config['url']);
                foreach ($deal as $key => $rows){
                    $response = $httpClient->get(sprintf('/api/v1/tasks/%s', $key));
                    if($response->isSuccess()){
                        $appInfo  = $response->toArray();
                        if (!empty($appInfo)){
                            if (!empty($appInfo['schoolIds'])){
                                $ids = array_column($appInfo['schoolIds'], 'schoolId');
                                $ids_arr = array_combine($ids, $appInfo['schoolIds']);
                                foreach ($rows as $schoolid){
                                    $return[$key][$schoolid] = $ids_arr[$schoolid];
                                }
                            }
                        }
                    }
                }
            }catch (\Exception $e){
                throw $e;
            }
        }
        return $return;
    }

    /**
     * 确认操作
     *
     * @return mixed
     *
     * create by qgz 2018/4/28
     */
    public function agreeAction(){
        $ids = $this->request->getPost('ids');
        if (empty($ids)){
            return $this->sendErrorResponse(400,'请选择后再操作！');
        }
        try {
            $params = [
                'conditions' => "iId in ($ids) and bDelete = 0",
            ];
            $data = XhappSchoolRelate::find($params);
            if (empty($data)){
                return $this->sendErrorResponse(500,'暂无数据！');
            }
            $this->db->begin();
            foreach ($data as $value){
                $value->bApprove = 1;
                $appPlanId = $value->iAppPlanId;
                if (!$value->save()){
                    $this->db->rollback();
                    return $this->sendErrorResponse(500,'操作出错！');
                }
            }
            $return = $this->checkAllAgree($appPlanId);
            if ($return[0] == 'error'){
                $this->db->rollback();
                if ($return[2]){
                    Main::createCommitLog('apprelease', 'agree', 'checkAllError', ['post' => $this->request->getPost()], null, $return[2]);
                }
                return $this->sendErrorResponse(500,$return[1]);
            }elseif ($return[0] == 'exist'){
                $this->db->commit();
                return $this->sendErrorResponse(500,'都已确认且任务已经下发，无需重复确认！');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('成功！');
        }catch (\Exception $e){
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 删除学校
     *
     * @return mixed
     *
     * create by qgz 2018/5/14
     */
    public function deleteSchoolAction(){
        $id = $this->request->getPost('id');
        $schoolIds = $this->request->getPost('schoolIds');
        if (empty($id) || empty($schoolIds)){
            return $this->sendErrorResponse(400,'请选择后再操作！');
        }
        $userid = User::getId();
        $modifyTime = date('Y-m-d H:i:s', time());
        try{
            $findData = XhappReleasePlan::findFirst([
                'columns' => 'sAppId, sPlanId, bDownLoad, bInstall',
                'conditions' => 'bDelete = 0 AND iId = :iId: AND bDownLoad = 1',
                'bind' => ['iId' => $id]
            ]);
            $this->db->begin();
            if ($findData){//如果是已经下发下载任务，需要去掉任务中的这些学校
                if ($findData->bInstall == 1){
                    return $this->sendErrorResponse(500, '该任务已经安装，不可删除学校!');
                }
                $planId = $findData->sPlanId;
                $schoolIdArr = explode(',', $schoolIds);
                $schoolIdArr = ['removeSchools' => $schoolIdArr];
                $config = Main::getConfigByName('jAppServer');
                $httpClient = new HttpClient($config['url']);
                $response = $httpClient->post(sprintf('/api/v1/tasks/%s/schools/reduce', $planId), $schoolIdArr);
                if (!$response->isSuccess()){
                    $this->db->rollback();
                    $msg = json_decode($response->body, true);
                    Main::createCommitLog('apprelease', 'deleteSchool', 'delSchool', ['post' => $this->request->getPost()], null, json_encode(['planid' => $planId, 'schoolids' => $schoolIdArr, 'return' => $msg['msg']]));
                    return $this->sendErrorResponse(500, '删除出错,接口错误:'.$msg['msg']);
                }
            }
            $sql = "UPDATE Admin\Models\app\XhappSchoolRelate SET bDelete = 1 , iLastModifyUserId = $userid , tLastModifyDate = "."'".$modifyTime."'"." WHERE iAppPlanId = {$id} AND iSchoolId in ({$schoolIds}) " ;
            if (!$this->modelsManager->executeQuery($sql)){
                $this->db->rollback();
                return $this->sendErrorResponse(500, '去除出错!');
            }else{
                $this->db->commit();
                return $this->sendSuccessResponse('成功！');
            }

        }catch(\Exception $e){
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 检查是否是全部确认，是则创建下载任务
     *
     * @return array
     *
     * create by qgz 2018/4/28
     */
    public function checkAllAgree($planId){
        $parameters  = [
            'columns' => 'iId, iSchoolId, sSchoolName, bApprove',
            'conditions' => "bDelete = 0 AND iAppPlanId = {$planId} ",
        ];
        $data = XhappSchoolRelate::find($parameters)->toArray();
        if (empty($data)){
            return ['success'];
        }
        $exit = false;
        foreach($data as $value){
            $schooArr[] = ['id' => $value['iSchoolId'], 'schoolName' => $value['sSchoolName']];
            if ($value['bApprove'] == 0){
                $exit = true;
            }
        }
        if (!$exit){//如果全部确认，则条用Java接口创建任务
            $parameters  = [
//                'columns' => 'iId, sPackageName, sVersionCode, sPlanId, bDownLoad ',
                'columns' => '*',
                'conditions' => "bDelete = 0 AND iId = {$planId} ",
            ];
            $data = XhappReleasePlan::findFirst($parameters);
            if ($data->bDownLoad == 1){
                return ['exist'];
            }
            $versionCode = $data->sVersionCode;
            $packageName = $data->sPackageName;
            $schoolInfo = ['schools' => $schooArr, 'taskName'=> ''];
            try{
                if (empty($versionCode) || empty($packageName)){
                    return ['error', '没有应用信息！'];
                }
                $config = Main::getConfigByName('jAppServer');
                $httpClient = new HttpClient($config['url']);
                $response = $httpClient->fullResponse()->postJson(sprintf('/api/v1/apps/%1$s/versions/%2$s/schools/tasks/', $packageName, $versionCode), $schoolInfo);
                if(!$response->isSuccess()){
                    $body = $response->body;
                    $body = json_decode($body.'}',true);
                    return ['error', '数据接口错误：'.$body['msg'], $body['msg']];
                }
                $taskid = explode('/', $response->responseHeader['Location']);
                $taskid = end($taskid);
                if (!$taskid){
                    return ['error', '接口数据为空！', $response->responseHeader['Location']];
                }
                $data->sPlanId = $taskid;
                $data->bDownLoad = 1;
                if (!$data->save()){
                    return ['error', '保存任务失败！'];
                }
            }catch(\Exception $e){
                return ['error', $e->getMessage()];
            }
        }
        return ['success'];
    }

    /**
     * 脚本--检测当天是否有可安装应用，有则安装
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20180625
     */
    public function runAppPlanInstallAction(){
        $data = XhappReleasePlan::find([
            'columns' => 'iId, sAppId, sPlanId, tReleaseDate, bDownLoad, bInstall',
            'conditions' => 'sPlanId IS NOT NULL AND bInstall = 0 AND bDelete = 0 AND tReleaseDate = :date: ',
            'bind' => ['date' => date('Y-m-d', time())]
        ])->toArray();
        if ($data){
            $config = Main::getConfigByName('jAppServer');
            foreach ($data as $value){
                $httpClient = new HttpClient($config['url']);
                $response = $httpClient->put('/api/v1/tasks/'.$value['sPlanId'].'/execute');
                if(!$response->isSuccess()){
                    $body = $response->toObject();
                    return $this->sendErrorResponse(500, '接口调用失败：'.$body->msg);
                } else {
                    try{
                        $sql = "UPDATE XHApp_ReleasePlan SET bInstall = 1 WHERE iId = ".$value['iId'];
                        $data = $this->db->execute($sql);
                        if (!$data) {
                            return $this->sendErrorResponse(500, '保存失败：iId='.$value['iId'].';appId='.$value['sPlanId']);
                        }
                    }catch (\Exception $e){
                        return $this->sendErrorResponse(500, '保存失败：'.$e->getMessage());
                    }
                }
            }
            return $this->sendSuccessResponse('检测完成');
        } else {
            return $this->sendSuccessResponse('没有需安装的应用');
        }
    }
}

